from rest_framework.exceptions import APIException
from rest_framework.views import exception_handler
# from rest_framework.exceptions import ErrorDetail
from rest_framework.utils.serializer_helpers import ReturnDict


def custom_exception_handler(exc, content):
    # detail = error_message = exc.detail
    try:
        detail = error_message = exc.detail
    except AttributeError:
        detail = error_message = '服务器出错'
    # 当异常来自serializer时 提取异常信息
    if isinstance(detail, ReturnDict):
        error_message = ''
        for filed, error in detail.items():
            error_message += filed + ' : ' + error[0] + '\n'
    response = exception_handler(exc, content)
    if response is not None:
        response.data.clear()
        response.data['status_code'] = response.status_code
        response.data['message'] = error_message
    return response


class BaseException(APIException):
    status_code = 400
    default_detail = '请求失败'
    default_code = 'invalid request'


class UserNotFind(BaseException):
    default_detail = '没有查询到相关用户'


class WrongPassword(BaseException):
    default_detail = '密码错误'


class ParamError(BaseException):
    default_detail = '缺少参数'
    status_code = 400


class Unauthorized(BaseException):
    status_code = 401
    default_detail = '没有登陆，请先登录'


class PermissionDenied(BaseException):
    status_code = 403
    default_detail = '没有权限'


class ObjectNotFound(BaseException):
    status_code = 404


class ServerError(BaseException):
    status_code = 500


class InvalidVerifyCode(BaseException):
    status_code = 400
    default_detail = '无效的验证码'


class ErrorCode:
    UNAUTHORIZED = 10000 # 未登录
    PERMISSION_DENIED = 10001 # 无权限
    PARAM_ERROR = 40000  # 参数验证错误
    DATA_NOT_FOUND = 40001  # 未找到数据
    DATA_NOT_VALID = 40002  # 数据错误
    REPEAT_POST = 40003  # 重复提交
    EEEE = 40003  # 新型错误

